package utils.utilcode.blankj.com.myapplication;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    // 设置搜狗
    public static final int SET_SOUGOU = 109;
    // 获取小雪APK名称
    public static final int IN_APK = 106;
    /**
     * 设置搜狗输入法为默认输入法
     */
    private static final String SET_SOUGOU_DEF = "settings put secure default_input_method com.sohu.inputmethod.sogou/.SogouIME";

    /**
     * 安装命令
     */
    private static final String INSTALL_APK = "pm install -r ";
    private static final int IN_FILE = 521;
    private static final int IN_CON = 520;
    private static final int COMETE = 1314;
    private static final int COPY_SHARED = 111;
    private static final int COPY_OK = 555;
    private static final int COPY = 232;

//
//    /**
//     * 文件1将要复制的地址
//     */
//    private String voicenoteToPath = "/mnt/sdcard/";
//
//    /**
//     * 文件2将要复制的地址
//     */
//    private String voicenoteDataToPath = "/data/data/com.iflytek.vflynote/";

//
    /**
     * //     * 文件1名称
     * //
     */
//    private String voicenote = "voicenote";
//    /**   *
//     */
    private File file;

    /**
     * 文件2名称
     */
//    private String voicenoteData = "voicenote_data";

    /**
     * 文件1复制命令
     */
    private String voicenoteCmd = "";
    /**
     * 文件2复制命令
     */
    private String voicenoteDataCmd = "";

    /**
     * 挂载路径(U盘)
     */
    private String apkName;

    private int apknumber;

private  int currentProgress;
    private String voicenote_vocice;
    private String voicenoteToPath = "/sdcard";
    private String deploy;
    private String voicenote_deployToPath = "/data/data/com.iflytek.vflynote";
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //   installapk(msg);
            //复制文件
            switch (msg.what) {
                case COPY_SHARED:
                    tv_msg.setText("正在配置讯飞语记");

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            for (String s : mFileList) {
                                if (s.contains("shared_prefs")) {
                                    //copy voicenote至sd卡
                                    deploy = "cp -r " + file + "/" + s + " " + voicenote_deployToPath;

                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            exec(deploy, COPY_OK);

                                        }
                                    }).start();
                                }
                            }
                        }
                    }).start();

                    break;

                case COPY_OK:
                    tv_msg.setText("即将重启...");
                    progressbar.setProgress(100);
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            uninstallSelfAndReboot();

                        }
                    }, 1000);


                    break;
//                case IN_CON:
//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//                            exec(voicenoteDataCmd, COMETE);
//                        }
//                    }).start();
//                    break;
//                case IN_FILE:
//                    tv_msg.setText("正在复制文件voicenote_data...");
//                    progressbar.setProgress(99);
//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//
//
//                            exec(voicenoteDataCmd, COMETE);
//                        }
//                    }).start();
//                    break;
                case IN_CON:
//                    Toast.makeText(MainActivity.this, "安装全部完成", Toast.LENGTH_SHORT).show();
                    // 判断所有操作是否正常被完成,否则重新开始操作
                    tv_msg.setText("开始复制讯飞语记离线发音人");
                    file = new File("mnt/usb_storage/kdxf");
                    mFileList = new ArrayList<>();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            File[] files = file.listFiles();
                            for (File f : files) {
                                mFileList.add(f.getName());
                            }

                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            //copy文件
                            for (String s : mFileList) {
                                if (s.contains("voicenote")) {
                                    //copy voicenote至sd卡
                                    voicenote_vocice = "cp -r " + file + "/" + s + " " + voicenoteToPath;
                                    exec(voicenote_vocice, COPY_OK);
                                }
                            }

//                            mHandler.obtainMessage(COPY).sendToTarget();
                        }
                    }).start();

//                    tv_msg.setText("正在重启...");
                    // 卸载自身并重启机器
//                    uninstallSelfAndReboot();
                    break;
                case SET_SOUGOU:
                    tv_msg.setText("正在配置搜狗输入法...");
                    progressbar.setProgress(99);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {

                            exec(SET_SOUGOU_DEF, IN_CON);
                        }
                    }).start();
                    break;

                case IN_APK:
                    progressbar.setProgress(5);
                    installapk(msg);
                    break;
            }
        }
        private void installapk(Message msg) {

            if (apknumber >= mList.size()) {
                System.out.println("设置搜狗");
                mHandler.obtainMessage(SET_SOUGOU).sendToTarget();
                return;
            }
            apkName = mList.get(apknumber);
            tv_msg.setText("正在安装" + apkName + "...");
            if (apknumber == (mList.size() - 1)) {
                progressbar.setProgress(95);
            } else {
                progressbar.setProgress(100 * (apknumber + 1) / mList.size());
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    exec(INSTALL_APK + file + "/" + apkName, IN_APK);
                }
            }).start();


        }
    };
    TextView tv_msg = null;
    ProgressBar progressbar = null;
    private ArrayList<String> mList;
    private List<String> mFileList;
    private  long totalSize;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        mList = new ArrayList<>();
        tv_msg = (TextView) findViewById(R.id.tv_msg);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        tv_msg.setText("正在下载...");
        getFile();
    }

    private void getFile() {
        file = new File("mnt/usb_storage/shengchan");
         totalSize=getFileSize();
        if (!file.exists()) {
            Toast.makeText(this, "U盘不存在", Toast.LENGTH_SHORT).show();
            return;
        }

//        Toast.makeText(this, file.exists() + "", Toast.LENGTH_SHORT).show();
//        if (!file.exists()) {
//            Toast.makeText(MainActivity.this, "U盘不存在", Toast.LENGTH_SHORT).show();
//            return;
//        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                File[] files = file.listFiles();
                for (File f : files) {
                    String fileName = f.getName();
//                    if (fileName.equals(voicenote) || fileName.equals(voicenoteData)) {
//                        //复制voicenote
//                        voicenoteCmd = "cp -r " + file + "/" + voicenote + " " + voicenoteToPath;
//                        voicenoteDataCmd = "cp -r " + file + "/" + voicenoteData + " " + voicenoteDataToPath;
//                    } else if (fileName.contains("TE_SnowBot_V")) {
//                        mList.add(0, fileName);
//                    } else {
                    mList.add(fileName);
//                    }
                }

                mHandler.obtainMessage(IN_APK).sendToTarget();
            }
        }).start();


    }

    private long getFileSize() {
        return file.length()+  new File("mnt/usb_storage/kdxf").length();
    }

    /**
     * 判断讯飞,小雪apk是否安装成功,讯飞目录是否正常被复制
     */
//    public boolean isExists() {
//        File snowFile = new File("/data/data/com.csjbot.snowbot");
//
////        Log.d("test", "===voicenoteFile==" + voicenoteFile.exists());
////        Log.d("test", "===voicenoteDataFile==" + voicenoteDataFile.exists());
////        Log.d("test", "===snowFile==" + snowFile.exists());
//        return (voicenoteFile.exists() && voicenoteDataFile.exists() && snowFile.exists());
//    }
    private void exec(String cmd, int code) {
        Log.e("MainActivity", cmd);

        InputStream is = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        DataOutputStream dos = null;
        try {
            Process process = Runtime.getRuntime().exec("su");
            dos = new DataOutputStream(process.getOutputStream());
            dos.write(cmd.getBytes());
            dos.write("\n".getBytes());
            dos.write("exit\n".getBytes());
            dos.flush();
            int status = process.waitFor();
            is = process.getErrorStream();
            inputStreamReader = new InputStreamReader(is);
            bufferedReader = new BufferedReader(inputStreamReader);
            String line = "";
            StringBuilder sb = new StringBuilder(line);
            while ((line = bufferedReader.readLine()) != null) {
                Log.d("test", "==line===" + line);
                sb.append(line);
                sb.append("\n");
            }
            Log.d("test", "=======status" + status);
            if (status == 0) {
                Log.e("MainActivity", "完成" + code);

                apknumber++;
//                if (apknumber >= mList.size()) {
//                    return;
//                }
                mHandler.obtainMessage(code).sendToTarget();
            }
            Log.d("test", "sb=====" + sb.toString());
        } catch (Exception e) {
            Log.e("test", "" + e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 卸载自身并重启
     */
    private void uninstallSelfAndReboot() {
        DataOutputStream dos = null;
        try {
            Process process = Runtime.getRuntime().exec("su");
            dos = new DataOutputStream(process.getOutputStream());
            dos.write("pm uninstall utils.utilcode.blankj.com.myapplication".getBytes());
            dos.write("\n".getBytes());
            dos.flush();
            dos.write("reboot".getBytes());
            dos.write("\n".getBytes());
            dos.write("exit\n".getBytes());
            dos.flush();
            dos.close();
        } catch (Exception e) {
            Log.e("test", "" + e);
        }
    }

    @Override
    public void onBackPressed() {
    }

    @Override
    protected void onDestroy() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }
}